/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 StdDataTypesCoderGrammar.cpp. Created on: 03.11.2010 18:59:45 
 */

#include "smartobjects/coders/StdDataTypesCoderGrammar.hpp"

namespace smartobjects {

StdDataTypesCoderGrammar::StdDataTypesCoderGrammar() {
}

StdDataTypesCoderGrammar::~StdDataTypesCoderGrammar() {
}

void StdDataTypesCoderGrammar::serialize(IDataTypesCoder* poCoder, IDataEncrypter* poEncrypter, ByteBuffer* poToBuffer) const {

	poCoder->encodeObjectMap(m_mStorage.size(), poToBuffer);
	for(GrammarStorage::left_const_iterator it = m_mStorage.left.begin(); it!=m_mStorage.left.end(); it++) {
		poCoder->encodeString(it->first, poToBuffer);
		poCoder->encodeUInt32(it->second, poToBuffer);
	}

}

void StdDataTypesCoderGrammar::deserialize(IDataTypesCoder* poCoder, IDataEncrypter* poEncrypter, ByteBuffer* poFromBuffer) {
	unsigned int nSize = poCoder->decodeObjectMap(poFromBuffer);
	for(unsigned int i=0; i<nSize; i++ ) {
		std::string sValue;
		poCoder->decodeString(sValue, poFromBuffer);
		boost::uint32_t nId = poCoder->decodeUInt32(poFromBuffer);
		m_mStorage.left.insert(GrammarStorage::left_value_type(sValue, nId));
	}
}

const std::string& StdDataTypesCoderGrammar::getObjectType() const {
	const static std::string sObjectType = "StdDataTypesCoderGrammar";
	return sObjectType;
}

unsigned int StdDataTypesCoderGrammar::registerGrammarElement(const std::string& sNamedObject) {
	unsigned int nResult = 0;
	GrammarStorage::left_const_iterator it= m_mStorage.left.find(sNamedObject);
	if(it!= m_mStorage.left.end()) {
		nResult = it->second;
	}
	else {
		nResult = m_mStorage.size() + 1;
		m_mStorage.left.insert(GrammarStorage::left_value_type(sNamedObject, nResult));
	}
	return nResult;
}

const std::string& StdDataTypesCoderGrammar::findGrammarElement(int nId) {
	static std::string sNullStr;
	GrammarStorage::right_iterator it= m_mStorage.right.find(nId);
	if(it!= m_mStorage.right.end()) {
		return it->second;
	}
	return sNullStr;
}

void StdDataTypesCoderGrammar::reset() {
	m_mStorage.clear();
}

}
